/**
 * Project: springyounger.lottery.web
 * 
 * File Created at 2010-4-8
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.util.ParamEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.LotteryPhase;
import com.springyounger.lottery.dal.dataobject.LotteryPrize;
import com.springyounger.lottery.dal.dataobject.LotteryPrizeQuota;
import com.springyounger.lottery.service.PrizeService;
import com.springyounger.lottery.service.user.PhaseService;

/**
 * 奖品管理
 * 
 * @author springyounger
 */
public class AdminPrizeController extends MultiActionController {
	private static final Logger logger = LoggerFactory
			.getLogger(AdminPrizeController.class);
	private PrizeService prizeService;
	private PhaseService phaseService;

	@SuppressWarnings("unchecked")
	public ModelAndView displayInsert(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 当前日期
		Date today = LotteryUtil.getToday();
		// 显示增加页面
		Map model = new HashMap();
		List<LotteryPhase> allPhaseList = phaseService.getPhases();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		// 得到今天之后的活动列表
		for (LotteryPhase phase : allPhaseList) {
			if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
				// 检查是否已经创建奖品配额
				List<LotteryPrizeQuota> quotaList = prizeService
						.getAllPrizesByPhaseId(phase.getPhaseId());
				if (quotaList.size() != 0 && null != quotaList.get(0)) {
					// 取出一个奖品进行验证
					LotteryPrizeQuota quota = quotaList.get(0);
					LotteryPrizeQuota verifyQuota = prizeService
							.getTopPrizeQuota(quota.getPrizeId());
					if (null == verifyQuota) {
						// 没有创建配额,活动可用
						logger.info("没有创建配额");
						phaseList.add(phase);
					}
				} else {
					phaseList.add(phase);
				}
			}
		}
		model.put("phaseList", phaseList);
		return new ModelAndView("admin/prizeInsertAndUpdate", model);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView insertAndUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map model = new HashMap();
		String prizeId = request.getParameter("id");

		// 奖品内容
		String prizeName = request.getParameter("prizeName");
		String phaseId = request.getParameter("phaseId");
		String prizeLevel = request.getParameter("prizeLevel");
		String prizePrice = request.getParameter("prizePrice");

		LotteryPrize prize = new LotteryPrize();
		prize.setPhaseId(Integer.parseInt(phaseId));
		prize.setPrizeName(prizeName);
		prize.setPrizeLevel(prizeLevel);
		if (LotteryUtil.isEmpty(prizePrice)) {
			prize.setPrizePrice("0");
		} else {
			prize.setPrizePrice(prizePrice);
		}

		model.put("prize", prize);

		if (prizeId.equals("") || prizeId.equals("0")) {
			// 是否重复
			if (prizeService.isExistPrize(prize)) {
				// 当前日期
				Date today = LotteryUtil.getToday();
				List<LotteryPhase> allPhaseList = phaseService.getPhases();
				List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
				// 得到今天之后的活动列表
				for (LotteryPhase phase : allPhaseList) {
					if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
						phaseList.add(phase);
					}
				}
				model.put("phaseList", phaseList);
				model.put("message", "该奖品已经存在!");
				return new ModelAndView("admin/prizeInsertAndUpdate", model);
			}
			// 创建
			prizeService.insertPrize(prize);
		} else {
			LotteryPrize verifyPrize = prizeService.getPrizeById(Integer
					.parseInt(prizeId));
			// 与原来名称不一致,进行题目重复检查
			if (!prizeName.equals(verifyPrize.getPrizeName())
					&& !prizeLevel.equals(verifyPrize.getPrizeLevel())) {
				// 是否重复
				if (prizeService.isExistPrize(prize)) {
					// 当前日期
					Date today = LotteryUtil.getToday();
					List<LotteryPhase> allPhaseList = phaseService.getPhases();
					List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
					// 得到今天之后的活动列表
					for (LotteryPhase phase : allPhaseList) {
						if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
							phaseList.add(phase);
						}
					}
					model.put("phaseList", phaseList);
					model.put("message", "该奖品已经存在!");
					return new ModelAndView("admin/prizeInsertAndUpdate", model);
				}
			}
			// 修改
			prize.setPrizeId(Integer.parseInt(prizeId));
			prizeService.updatePrize(prize);
		}
		return findByAll(request, response);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView findByAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 当前日期
		Date today = LotteryUtil.getToday();
		Map model = new HashMap();
		// 页数的参数名
		String pageIndexName = new ParamEncoder("row")
				.encodeParameterName(org.displaytag.tags.TableTagParameters.PARAMETER_PAGE);
		// 每页显示的条数
		int pageSize = 10;
		// 当前页
		int pageIndex = LotteryUtil
				.isEmpty(request.getParameter(pageIndexName)) ? 0 : (Integer
				.parseInt(request.getParameter(pageIndexName)) - 1);
		// 总记录
		int resultSize = prizeService.getAllPrizesCount();
		List<LotteryPrize> prizeList = prizeService.getAllPrizes(pageIndex,
				pageSize);
		List<LotteryPhase> phaseList = phaseService.getPhases();
		// 设置活动名称
		for (int i = 0; i < prizeList.size(); i++) {
			LotteryPrize prize = prizeList.get(i);
			for (int j = 0; j < phaseList.size(); j++) {
				if (prize.getPhaseId() == phaseList.get(j).getPhaseId()) {
					// 设置
					prize.setPhaseName(phaseList.get(j).getPhaseName());
					// 是否激活(正在活动中或者过期的设置为 y,未开始的设置为 n)
					if (LotteryUtil.getQuot(today, phaseList.get(j)
							.getGmtStart()) > 0) {
						// 未开始
						prize.setIsActivity("n");
						// 检查是否已经创建奖品配额
						List<LotteryPrizeQuota> quotaList = prizeService
								.getAllPrizesByPhaseId(phaseList.get(j)
										.getPhaseId());
						// 取出一个奖品进行验证
						LotteryPrizeQuota quota = quotaList.get(0);
						LotteryPrizeQuota verifyQuota = prizeService
								.getTopPrizeQuota(quota.getPrizeId());
						if (null == verifyQuota) {
							// 没有创建配额,活动可用
							prize.setHaveQuota("n");
						} else {
							prize.setHaveQuota("y");
						}
					} else {
						prize.setIsActivity("y");
					}
				}
			}
		}

		model.put("resultSize", resultSize);
		model.put("prizeList", prizeList);
		return new ModelAndView("admin/prizeList", model);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView findById(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map model = new HashMap();

		String id = request.getParameter("id");
		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			return findByAll(request, response);
		}
		int prizeId = Integer.parseInt(id);
		LotteryPrize prize = prizeService.getPrizeById(prizeId);
		// 当前日期
		Date today = LotteryUtil.getToday();
		// 显示增加页面
		List<LotteryPhase> allPhaseList = phaseService.getPhases();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		// 得到今天之后的活动列表
		for (LotteryPhase phase : allPhaseList) {
			if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
				phaseList.add(phase);
			}
		}

		model.put("phaseList", phaseList);
		model.put("prize", prize);

		return new ModelAndView("admin/prizeInsertAndUpdate", model);
	}

	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			logger.info("活动id异常");
			return findByAll(request, response);
		}
		int prizeId = Integer.parseInt(id);
		LotteryPrize prize = prizeService.getPrizeById(prizeId);

		// 活动
		LotteryPhase phase = phaseService.getPhaseById(prize.getPhaseId());
		if (phase.getIsActivity().equals("y")) {
			return new ModelAndView("admin/prizeList", "message",
					"活动正在进行中,不能更改");
		}

		prizeService.deletePrize(prizeId);
		return findByAll(request, response);
	}

	/**
	 * @param prizeService
	 *            the prizeService to set
	 */
	public void setPrizeService(PrizeService prizeService) {
		this.prizeService = prizeService;
	}

	/**
	 * @param phaseService
	 *            the phaseService to set
	 */
	public void setPhaseService(PhaseService phaseService) {
		this.phaseService = phaseService;
	}
}
